package com.leetroll.media.job;

import com.leetroll.api.service.ItemService;
import com.leetroll.common.entity.Item;
import com.leetroll.common.enums.EFileType;
import com.leetroll.common.enums.EItemType;
import com.leetroll.media.service.JobExecutor;
import com.leetroll.media.service.UpDownloadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ExecutionException;

@Service
@Slf4j
public class Job_Image {

    private static final String TO_DB_FILE_PATH = "F:\\_resources\\texture\\CM 423540 - Vintage Paper Textures Mega Pack";
    private final ItemService itemService;
    private final UpDownloadService upDownloadService;
    private JobExecutor jobExecutor;

    @Autowired
    public Job_Image(ItemService itemService, UpDownloadService upDownloadService, JobExecutor jobExecutor) {
        this.itemService = itemService;
        this.upDownloadService = upDownloadService;
        this.jobExecutor = jobExecutor;
    }

    public void upload() throws InterruptedException, IOException, ExecutionException {
        File folder = new File(TO_DB_FILE_PATH);
        if (!folder.exists() || !folder.isDirectory()) return;

        File[] itemsFiles = folder.listFiles();
        if (itemsFiles == null) return;

        for (File itemsFile : itemsFiles) {
            jobExecutor.submit(() -> uploadFile(itemsFile));
        }
        jobExecutor.await();
    }

    private Integer uploadFile(File itemFile) {
        log.info("----------------------准备插入 item[{}]----------------------", itemFile.getName());

        //插入item表
        String name = itemFile.getName();
        Item item = new Item();
        item.setName(name);
        item.setAlias(name);
        item.setCatId(6L);
        item.setStatus("show");
        item.setSource("CM 423540");
        item.setAuthor("橄榄枝_");
        item.setPrice(0.0);
        item.setMark("");
        item.setType(EItemType.IMAGE.getType());
        item.setDesp("Vintage Paper Textures Mega Pack");
        item.setTag("paper");
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);


        //插入主图文件
        upDownloadService.upload2AliByType(item.getId(), itemFile, EFileType.MAIN);
        log.info("\t\t\t>> 主图插入成功");

        return 1;
    }

}
